在 Vue 3.5 及以上版本中,从 返回值解构出的变量是响应式的defineProps
const { foo } = defineProps(['foo'])
watchEffect(() => {
// 在 3.5 之前仅运行一次
// 在 3.5+ 版本中会在 "foo" prop 改变时重新运行
console.log(foo)
})当在同一个 块中的代码访问从 <script setup> 解构出的变量时,Vue 的编译器会自动在前面添加 definePropsprops.
const props = defineProps(['foo'])
watchEffect(() => {
// `foo` 由编译器转换为 `props.foo`
console.log(props.foo)
})3.4 及以下
interface Props {
labels?: string[]
msg?: string
}
const props = withDefaults(defineProps<Props>(), {
labels: () => ['one', 'two'], // 注意要使用函数
msg: 'hello'
})3.5 及以上
interface Props {
labels?: string[]
msg?: string
}
const { labels = ['one', 'two'], msg = 'hello' } = defineProps<Props>()[@vue/compiler-sfc] withDefaults() is unnecessary when using destructure with defineProps().